package com.example.houseitemmanagebackend.controller;

import com.example.houseitemmanagebackend.dto.AddUserToLocationRequestDTO;
import com.example.houseitemmanagebackend.dto.UserLocationDTO;
import com.example.houseitemmanagebackend.entity.UserLocation;
import com.example.houseitemmanagebackend.entity.Users;
import com.example.houseitemmanagebackend.entity.Locations;
import com.example.houseitemmanagebackend.service.LocationService;
import com.example.houseitemmanagebackend.service.UserLocationService;
import com.example.houseitemmanagebackend.service.UserService;
import com.example.houseitemmanagebackend.vo.Result;
import com.example.houseitemmanagebackend.vo.UserLocationRoleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userLocations")
@RequiredArgsConstructor
public class UserLocationController {

    private final UserLocationService userLocationService;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final LocationService locationService;

    /**
     * 添加用户到位置，需要提供用户名和密码进行验证。
     */
    @PostMapping("/add")
    public Result<?> addUserToLocation(@RequestBody AddUserToLocationRequestDTO dto) {
        // 1. Find user by username
        Users user = userService.getUserByUsername(dto.getUsername());
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 2. Verify password
        if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 3. Add user to location
        userLocationService.addUserToLocation(user.getId(), dto.getLocationId(), dto.getRoleType());
        return Result.success("用户已成功添加到位置");
    }

    /**
     * 更新用户在位置中的角色
     */
    @PutMapping("/updateRole")
    public Result<Boolean> updateUserLocationRole(@RequestBody UserLocationDTO dto) {
        boolean result = userLocationService.updateUserLocationRole(
                dto.getUserId(), dto.getLocationId(), dto.getRoleType());
        return Result.success(result);
    }

    /**
     * 获取位置的所有用户及其角色
     */
    @GetMapping("/users/{locationId}")
    public Result<List<UserLocationRoleVO>> getUsersByLocationId(@PathVariable Integer locationId) {
        // 获取该位置的所有用户-位置关系
        List<UserLocation> userLocations = userLocationService.getUserLocationsByLocationId(locationId);
        if (userLocations.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 提取用户ID列表
        List<Integer> userIds = userLocations.stream()
                .map(UserLocation::getUserId)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取用户信息
        Map<Integer, Users> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(Users::getId, user -> user));

        // 构建包含角色信息的VO列表
        List<UserLocationRoleVO> resultList = userLocations.stream().map(ul -> {
            Users user = userMap.get(ul.getUserId());
            return new UserLocationRoleVO(user, ul.getRoleType());
        }).collect(Collectors.toList());

        return Result.success(resultList);
    }

    /**
     * 获取用户的所有位置
     */
    @GetMapping("/locations/{userId}")
    public Result<List<Locations>> getLocationsByUserId(@PathVariable Integer userId) {
        // 获取用户的所有位置ID
        List<Integer> locationIds = userLocationService.getLocationsByUserId(userId);

        // 获取用户的位置列表
        List<Locations> locations = new ArrayList<>();
        // 这里我们通过获取用户的所有位置列表，然后过滤出我们需要的位置
        // 如果LocationService提供了根据ID列表获取位置的方法，可以直接调用
        List<Locations> allUserLocations = locationService.getLocationList(userId);
        for (Locations location : allUserLocations) {
            if (locationIds.contains(location.getId())) {
                locations.add(location);
            }
        }

        return Result.success(locations);
    }

    /**
     * 从位置中移除用户
     */
    @DeleteMapping("/remove")
    public Result<Boolean> removeUserFromLocation(@RequestParam Integer userId, @RequestParam Integer locationId) {
        boolean result = userLocationService.removeUserFromLocation(userId, locationId);
        return Result.success(result);
    }

    /**
     * 获取用户与其所有位置的关系信息
     */
    @GetMapping("/permissions/{userId}")
    public Result<Map<Integer, Integer>> getUserLocationRelations(@PathVariable Integer userId) {
        List<Integer> locationIds = userLocationService.getLocationsByUserId(userId);
        Map<Integer, Integer> locationRoleMap = new HashMap<>();

        for (Integer locationId : locationIds) {
            Integer roleType = userLocationService.getUserRoleTypeInLocation(userId, locationId);
            locationRoleMap.put(locationId, roleType);
        }

        return Result.success(locationRoleMap);
    }
}